package com.medical.logback.handler;

import com.medical.logback.exception.BizException;
import com.medical.logback.response.Result;
import com.medical.logback.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther:gzf
 * @Date : 2022/06/23
 */
@Slf4j
@Component
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异", e);
        return Result.error(ResultCode.PARAM_NULL);
    }

    /**
     * 统一处理业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Result exceptionHandler(BizException e) {
        log.error("业务异常:", e);
        return Result.error(e.getErrorCode(),e.getErrorMsg());
    }


    /*
     * @Author: gzf
     * @Date: 2022/6/23
     * @Description: 未定义异常处理.
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = Exception.class)
    public Result handler(Exception e) {
        log.error("未知异常", e);
        return Result.error(ResultCode.ERROR);
    }

}
